package webapi

import (
	"server/internal/model"
	"server/internal/pkg/WxOfficialAccount"
	"server/internal/pkg/response"
	"server/internal/services"

	"github.com/gin-gonic/gin"
)

var LoginApi = new(loginApi)

// LoginApi 登录
type loginApi struct {
	model.User
}

// Router 路由
func (a loginApi) Router(r *gin.RouterGroup) {
	r.POST("/auth_login", a.authLogin)
}

// AuthLogin 微信授权登录
func (a loginApi) authLogin(c *gin.Context) {
	type Param struct {
		JsCode string `json:"js_code" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "", err.Error())
		return
	}

	login, err := WxOfficialAccount.AuthLogin(param.JsCode)
	if err != nil {
		response.Error(c, "", err.Error())
		return
	}

	user, ExpiresAt, err := services.Login.AuthLogin(c, login)

	user.ExpiresAt = ExpiresAt
	if err != nil {
		response.Error(c, "", err.Error())
		return
	} else {
		data := make(map[string]interface{})
		data["userinfo"] = user
		data["routePath"] = "/admin"
		response.Success(c, data, "登录成功")

	}

}
